<template>
  <div>
    <div class="addressform w">
      <div class="order-detail-area order-address">
        <div class="h order-address-header">
          <span>收货地址</span>
          <a
            href="javascript:;"
            class="address-add-btn"
            v-show="address.length != 0"
            @click="newaddress()"
          >
            <i class="iconfont" style="color: red">&#xe632;</i>
            新增收货地址</a
          >
        </div>
        <div class="order-address-list">
          <ul class="clearfix">
            <li
              class="current"
              v-for="(item, index) in CurrentAddress"
              :key="index"
            >
              <div class="address-main">
                <div class="clearfix consignee-main">
                  <b class="consignee-name">{{ item.rvname }}</b
                  ><b class="consignee-tel">{{ item.rvphone }}</b
                  ><b class="address-default-status" v-show="item.default"
                    >默认地址</b
                  >
                  <div class="address-sub">
                    <a
                      class="address-default"
                      :class="{ hide: item.default }"
                      href="javascript:;"
                      v-show="!item.default"
                      @click="setDefault(item.aid, true)"
                      >设为默认</a
                    ><a
                      class="address-edit"
                      href="javascript:;"
                      @click="EditAddress(item)"
                      >编辑</a
                    ><a
                      class="address-del"
                      href="javascript:;"
                      @click="Deletecurrent(item.aid)"
                      >删除</a
                    >
                  </div>
                </div>
                <div class="address-detail" id="address-detail-158467164">
                  {{ item.rvregion.province.value }}&nbsp;
                  {{ item.rvregion.city.value }}&nbsp;
                  {{ item.rvregion.area.value }}&nbsp;
                  {{ item.rvregion.deaddress }}
                </div>
              </div>
            </li>
          </ul>
          <div>
            <ul class="clearfix over-flow-scroll" v-show="allAddress">
              <li
                v-for="(item, index) in NoCurrentAddress"
                :key="index"
                @click="ClickCurrent(item.aid)"
              >
                <div class="address-main">
                  <div class="clearfix consignee-main">
                    <b class="consignee-name">{{ item.rvname }}</b
                    ><b class="consignee-tel">{{ item.rvphone }}</b
                    ><b class="address-default-status" v-show="item.default"
                      >默认地址</b
                    >
                    <div class="address-sub">
                      <a
                        class="address-default"
                        :class="{ hide: item.default }"
                        href="javascript:;"
                        v-show="!item.default"
                        @click.stop="setDefault(item.aid, true)"
                        >设为默认</a
                      ><a
                        class="address-edit"
                        href="javascript:;"
                        @click.stop="EditAddress(item)"
                        >编辑</a
                      ><a
                        class="address-del"
                        href="javascript:;"
                        @click.stop="DeleteAddress(item.aid)"
                        >删除</a
                      >
                    </div>
                  </div>
                  <div class="address-detail" id="address-detail-158467164">
                    {{ item.rvregion.province.value }}&nbsp;
                    {{ item.rvregion.city.value }}&nbsp;
                    {{ item.rvregion.area.value }}&nbsp;
                    {{ item.rvregion.deaddress }}
                  </div>
                </div>
              </li>
            </ul>
          </div>
        </div>

        <div class="order-address-list" :class="{ hide: address.length != 0 }">
          <ul class="clearfix">
            <li class="address-empty">
              <a
                href="javascript:;"
                @click="newaddress()"
                class="address-add-btn"
              >
                <i class="iconfont" style="color: red">&#xe632;</i
                >新增收货地址</a
              >
            </li>
          </ul>
        </div>

        <div class="f">
          <div>
            <a
              href="javascript:;"
              class="address-expand hide"
              @click="allAddress = !allAddress"
              :style="{ display: !allAddress ? 'inline' : 'none' }"
              >查看全部地址</a
            ><!--收缩class="address-shrink"-->
            <a
              href="javascript:;"
              class="address-shrink hide"
              @click="allAddress = !allAddress"
              :style="{ display: allAddress ? 'inline' : 'none' }"
              >收起地址</a
            >
          </div>
        </div>
      </div>
    </div>
    <!-- 添加地址表单 -->
    <el-dialog
      title="收货地址"
      :visible.sync="dialogFormVisible"
      id="dialogForm"
    >
      <el-form :model="AddressForm" ref="AddressForm" :rules="AddressRules">
        <el-form-item label="收货人" label-width="120px" prop="rvname">
          <el-input v-model="AddressForm.rvname" autocomplete="off"></el-input>
        </el-form-item>
        <div style="display: flex">
          <el-form-item label="手机号码" label-width="120px" prop="rvphone">
            <el-input
              v-model="AddressForm.rvphone"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="备选手机号"
            label-width="120px"
            prop="rvscendphone"
          >
            <el-input
              v-model="AddressForm.rvscendphone"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </div>
        <el-form-item label="收货地址" label-width="120px" :required="true">
          <v-distpicker @selected="regionSelect"></v-distpicker>
        </el-form-item>
        <el-form-item
          label="街道、小区等   "
          label-width="120px"
          prop="rvregion.deaddress"
        >
          <el-input
            type="textarea"
            :autosize="{ minRows: 1, maxRows: 4 }"
            placeholder="如果选择不到您的地区，请在此详细描述"
            v-model="AddressForm.rvregion.deaddress"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addAddress()">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 更新地址表单 -->
    <el-dialog title="收货地址" :visible.sync="updatedialogFormVisible">
      <el-form :model="UpdateForm" ref="UpdateForm" :rules="AddressRules">
        <el-form-item label="收货人" label-width="120px" prop="rvname">
          <el-input v-model="UpdateForm.rvname" autocomplete="off"></el-input>
        </el-form-item>
        <div style="display: flex">
          <el-form-item label="手机号码" label-width="120px" prop="rvphone">
            <el-input
              v-model="UpdateForm.rvphone"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="备选手机号"
            label-width="120px"
            prop="rvscendphone"
          >
            <el-input
              v-model="UpdateForm.rvscendphone"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </div>
        <el-form-item label="收货地址" label-width="120px" :required="true">
          <v-distpicker
            :province="UpdateForm.rvregion.province.value"
            :city="UpdateForm.rvregion.city.value"
            :area="UpdateForm.rvregion.area.value"
            @selected="updateregionSelect"
          ></v-distpicker>
        </el-form-item>
        <el-form-item
          label="街道、小区等   "
          label-width="120px"
          prop="rvregion.deaddress"
        >
          <el-input
            type="textarea"
            :autosize="{ minRows: 1, maxRows: 4 }"
            placeholder="如果选择不到您的地区，请在此详细描述"
            v-model="UpdateForm.rvregion.deaddress"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="updatedialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateAddress()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import VDistpicker from "v-distpicker";
import { validatePhone2 } from "../../../plugins/validator";
import { mapActions } from "vuex";
export default {
  components: {
    "v-distpicker": VDistpicker,
  },
  computed: {
    CurrentAddress: function () {
      return this.address.filter((item) => {
        return item.current;
      });
    },
    NoCurrentAddress: function () {
      return this.address.filter((item) => {
        return !item.current;
      });
    },
  },
  data() {
    return {
      xxxx: "",
      dialogFormVisible: false,
      updatedialogFormVisible: false,
      allAddress: false,
      AddressForm: {
        userid: this.$store.getters.UserInfoID,
        rvname: "",
        rvphone: "",
        rvscendphone: "",
        rvregion: {
          province: "",
          city: "",
          area: "",
          deaddress: "",
        },
      },
      UpdateForm: {
        rvname: "",
        rvphone: "",
        rvscendphone: "",
        rvregion: {
          province: "",
          city: "",
          area: "",
          deaddress: "",
        },
      },
      AddressRules: {
        rvname: [
          { required: true, trigger: "blur", message: "请填写收货人信息" },
        ],
        rvphone: [
          { required: true, validator: validatePhone2, trigger: "blur" },
        ],
        rvscendphone: [{ validator: validatePhone2, trigger: "blur" }],
        province: [{ required: true, trigger: "blur", message: "请选择省份" }],
        city: [{ required: true, trigger: "blur", message: "请选择城市" }],
        area: [{ required: true, trigger: "blur", message: "请选择区域" }],

        deaddress: [{ required: true, trigger: "blur" }],
      },
      address: [],
    };
  },
  methods: {
    ...mapActions(["setaddress"]),
    //地区选择方法
    regionSelect(data) {
      this.AddressForm.rvregion.province = data.province;
      this.AddressForm.rvregion.city = data.city;
      this.AddressForm.rvregion.area = data.area;
    },
    updateregionSelect(data) {
      this.UpdateForm.rvregion.province = data.province;
      this.UpdateForm.rvregion.city = data.city;
      this.UpdateForm.rvregion.area = data.area;
    },
    newaddress() {
      this.dialogFormVisible = true;
      this.AddressForm = {
        userid: this.$store.getters.UserInfoID,
        rvname: "",
        rvphone: "",
        rvscendphone: "",
        rvregion: {
          province: "",
          city: "",
          area: "",
          deaddress: "",
        },
      };
    },
    addAddress() {
      this.$refs.AddressForm.validate(async (valid) => {
        if (!valid) return false;
        else if (
          this.AddressForm.rvregion.province == "" ||
          this.AddressForm.rvregion.city == "" ||
          this.AddressForm.rvregion.area == ""
        ) {
          this.$message({
            type: "warning",
            message: "请填完地址",
          });
        } else {
          this.axios
            .post("/user/addAddress", {
              form: this.AddressForm,
            })
            .then((res) => {
              console.log(res);
              if (res.data.code == 200) {
                this.dialogFormVisible = false;
                this.address.forEach((e, index) => {
                  if (e.current) {
                    this.$set(this.address[index], "current", false);
                  }
                });
                this.address.push(res.data.data);
              }
            });
        }
      });
    },
    getAddress() {
      return new Promise((resolve, rej) => {
        this.axios
          .get("/user/getAddress", {
            params: {
              _id: this.$store.getters.UserInfoID,
            },
          })
          .then((res) => {
            // console.log(res);
            if (res.data.code == 200) {
              this.address = res.data.data;
              resolve(res.data.data);
            } else {
              rej(res.data);
            }
          })
          .catch((err) => {
            rej(err);
          });
      });
    },
    Deletecurrent(aid) {
      if (this.address.length != 1) {
        this.address.forEach((e, index) => {
          if (e.aid == aid) {
            this.address.splice(index, 1);
            this.axios.post("/user/deleteAddress", {
              userid: this.$store.getters.UserInfoID,
              aid: aid,
            });
          }
        });
        this.$set(this.address[0], "current", true);
        this.updateCurrent(this.address[0].aid, { current: true });
      } else {
        this.address.splice(0, 1);
        this.axios.post("/user/deleteAddress", {
          userid: this.$store.getters.UserInfoID,
          aid: aid,
        });
      }
    },
    ClickCurrent(aid) {
      let caid = this.CurrentAddress[0].aid;
      this.address.forEach((e, index) => {
        if (e.aid == caid) {
          this.$set(this.address[index], "current", false);
        }
        if (e.aid == aid) {
          this.$set(this.address[index], "current", true);
        }
      });
      this.updateCurrent(caid, false);
      this.updateCurrent(aid, true);
    },
    updateCurrent(aid, bool) {
      this.axios.post("/user/updateCurrent", {
        aid: aid,
        userid: this.$store.getters.UserInfoID,
        current: bool,
      });
    },
    setDefault(aid, bool) {
      this.address.forEach((e, index) => {
        if (e.default == true) {
          // this.updateDefault(e.aid,false)
          this.$set(this.address[index], "default", false);
        }
        if (e.aid == aid) {
          this.$set(this.address[index], "default", true);
        }
      });
      console.log(bool);
      // this.$set()
    },
    updateDefault(aid, bool) {
      this.axios.post("/user/updateDefault", {
        aid: aid,
        userid: this.$store.getters.UserInfoID,
        default: bool,
      });
    },
    EditAddress(item) {
      this.updatedialogFormVisible = true;
      // value为要拷贝对象 深拷贝不会修改原对象的值
      let item2 = JSON.parse(JSON.stringify(item));
      this.UpdateForm = item2;
    },
    updateAddress() {
      this.$refs.UpdateForm.validate(async (valid) => {
        if (!valid) return false;
        else if (
          this.UpdateForm.rvregion.province == "" ||
          this.UpdateForm.rvregion.city == "" ||
          this.UpdateForm.rvregion.area == ""
        ) {
          this.$message({
            type: "warning",
            message: "请填完地址",
          });
        } else {
          this.UpdateForm.date = Date.now();
          this.axios
            .post("/user/updateAddress", {
              form: this.UpdateForm,
            })
            .then((res) => {
              if (res.data.code == 200) {
                this.updatedialogFormVisible = false;
                this.address.forEach((e, index) => {
                  if (e.aid == this.UpdateForm.aid) {
                    this.$set(this.address, index, this.UpdateForm);
                  }
                });
              } else {
                this.$message({
                  type: "warning",
                  message: "更新失败",
                });
              }
            });
        }
      });
    },
    DeleteAddress(aid) {
      this.address.forEach((e, index) => {
        if (e.aid == aid) {
          this.address.splice(index, 1);
        }
      });
      this.axios.post("/user/deleteAddress", {
        userid: this.$store.getters.UserInfoID,
        aid: aid,
      });
    },
  },
  mounted() {
    this.xxxx = this.getAddress();
  },
};
</script>

<style>
#dialogForm .el-dialog__header {
  text-align: center;
}
#dialogForm .distpicker-address-wrapper label,
select {
  outline: none;
}
#dialogForm .el-form-item:nth-child(5) {
  width: 79%;
  /* margin: 0; */
  margin-left: 50px;
}
</style>